package com.quanyan.place.wrapper.impl;

import com.alibaba.dubbo.common.json.JSONObject;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.quanyan.api.APIResponse;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.enums.SysParameterConfigEnum;
import com.quanyan.common.utils.CommonUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.ShortUrlUtils;
import com.quanyan.orderpay.response.RespPreOrder;
import com.quanyan.place.biz.IBaseService;
import com.quanyan.place.biz.ISearchService;
import com.quanyan.place.cache.PlaceRedisTemplate;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.PlaceBuyContract;
import com.quanyan.place.entity.*;
import com.quanyan.place.entity.apireq.*;
import com.quanyan.place.entity.apiresp.*;
import com.quanyan.place.entity.vo.*;
import com.quanyan.place.mapper.TbBizPlaceUnitSalePlanMapper;
import com.quanyan.place.service.*;
import com.quanyan.place.service.impl.PlaceOrderCallbackServiceImpl;
import com.quanyan.place.wrapper.PlaceMessageWrapper;
import com.quanyan.place.wrapper.PlaceOrderServiceWrapper;
import com.quanyan.place.wrapper.PlaceWrapper;
import com.quanyan.redisCluster.utils.RedisConstants;
import com.quanyan.redisCluster.utils.RedisKey;
import com.quanyan.search.entity.vo.PlaceIndexInfo;
import com.quanyan.search.service.PlaceSearchService;
import com.quanyan.search.service.impl.PlaceSearchServiceImpl;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.apache.commons.collections.MapUtils;
import org.intellij.lang.annotations.JdkConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.thymeleaf.fragment.IFragmentSpec;
import sms.SmsApi;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.quanyan.place.constants.PlaceConstants.PLACE_CONTRACT_VERIFY_NO;
import static com.quanyan.place.service.impl.PlaceBuyServiceImpl.newPlaceBuyContractDetailFromTbDetail;

/**
 * 场馆wrapper实现
 * Created by yangyun on 16-6-6.
 */
@Service("placeMessageWrapper")
public class PlaceMessageWrapperImpl implements PlaceMessageWrapper {
    private static final Logger logger = LoggerFactory.getLogger(PlaceMessageWrapperImpl.class);

    @Autowired
    PlaceMessageService  placeMessageService;
    @Autowired
    PlaceTicketService placeTicketService;
    @Autowired
    PlaceBaseService placeBaseService;
    @Autowired
    UserServiceFacade userServiceFacade;
    @Autowired
    PlaceOrderService   placeOrderService;
    @Autowired
    PlaceOrderServiceWrapper placeOrderServiceWrapper;
    @Autowired
    PlaceInnerService placeInnerService;
    @Autowired
    AdminUserService adminUserService;
    @Autowired
    com.quanyan.place.biz.SmsService  placeSmsService;

    @Value("${html.service.bookingPlaceUrl}")
    private String bookingPlaceUrl;

    /**
     * 发送推广下发短信
     * @param reqPlaceMessageVo
     * @return
     */
    @Override
    public APIResponse<?> sendPromotionMessageData(ReqPlaceMessageVo reqPlaceMessageVo){
        APIResponse result;
        String jpgUrl="";
        Integer id=0;
        Integer categoryId=1;
        Integer cityId=0;
        String name="";
        String address="";
        String phone="";
        String category="";
        String tokenFlag="";
        String code="";
        List<Integer> categoryIds=new ArrayList<>();
        if (reqPlaceMessageVo.getMobile()!=null){
            result=APIResponse.returnFail("手机号码不能为空");
        }
        TbAdminUser userVo=adminUserService.getAdminUser(reqPlaceMessageVo.getUid());
        if (userVo==null||userVo.getBcCardno()==null){
            return APIResponse.returnFail("推广人的银行账号不能为空号");
        }
      /*  APIResponse resp=userServiceFacade.queryUserInfoByPhone(reqPlaceMessageVo.getMobile());
        if (resp.getData()==null){
            result=APIResponse.returnFail("请先在APP注册！");
        }*/
        //取出有定价的运动类别
        List<RespCategoryAndScale> categoryList =placeBaseService.getCategoryAndScale(reqPlaceMessageVo.getPlaceId(),true);
            for(int i=0;i<categoryList.size();i++){
                categoryIds.add(categoryList.get(i).getId());
            }
        //随机打乱
        Collections.shuffle(categoryIds);
        if (categoryIds!=null&&categoryIds.size()>0){
            categoryId=categoryIds.get(0);
            if (categoryId==1){
                category="篮球";
            }else if (categoryId==2){
                category="羽毛球";
            }else if (categoryId==3){
                category="足球";
            }else if (categoryId==4){
                category="网球";
            }
        }
        Integer uid=reqPlaceMessageVo.getUid();
        TbBizPlace place=placeBaseService.getPlaceById(reqPlaceMessageVo.getPlaceId());
        TbBizPlacePromotionRecord  vo=new TbBizPlacePromotionRecord();

        if (place!=null){
            jpgUrl=place.getBizPlaceUrl();
            id=place.getId();
            cityId=place.getCityId();
            name=place.getName();
            address=place.getAddress();
            phone=place.getPhone();
            code=place.getCode();
        }
        tokenFlag=code + CommonUtils.generateToken(uid);
        vo.setToken(tokenFlag);
        logger.info("vo.getToken()--->"+vo.getToken());
        vo.setMobile(reqPlaceMessageVo.getMobile());
        vo.setAccountNumber(reqPlaceMessageVo.getAccountNumber());
        vo.setPromotionDate(new Date());
        vo.setPlaceId(reqPlaceMessageVo.getPlaceId());
        vo.setUid(reqPlaceMessageVo.getUid());
        vo.setCategoryId(reqPlaceMessageVo.getCategoryId());
        placeMessageService.savePromotionRecord(vo);

        List<String> mobileList=new ArrayList<>();
        List<String> paramList=new ArrayList<>();
        //成功消费发送短信提醒
        String [] args=new String[1];
        args[0]="";
        String redirectUrl="";

        try{
             redirectUrl=bookingPlaceUrl+jpgUrl
                    +"&id="+id+"&categoryId="+categoryId+"&cityId="+cityId+"&name="+java.net.URLEncoder.encode(name,"utf-8")+"&address="+java.net.URLEncoder.encode(address,"utf-8")+"&phone="+java.net.URLEncoder.encode(phone,"utf-8")+"&category="+java.net.URLEncoder.encode(category,"utf-8")+"&tokenFlag="+java.net.URLEncoder.encode(tokenFlag,"utf-8");
        }catch(UnsupportedEncodingException e){
            e.printStackTrace();
        }
        //url= "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf45cb3432988261f&response_type=code&scope=snsapi_base&state=123&from=timeline&isappinstalled=0&redirect_uri="+urlEncode;
        logger.info("redirectUrl==="+redirectUrl);
        //转成短链接
        String urlObject= ShortUrlUtils.getShortUrl(redirectUrl);
        if (urlObject!=null){
            List<RespShareUrl> respShareUrls = JSON.parseArray(urlObject, RespShareUrl.class);
            args[0]=respShareUrls.get(0).getUrl_short();
        }
        logger.info("args[0] ==="+args[0]);

        mobileList.add(reqPlaceMessageVo.getMobile());
        paramList.addAll(Arrays.asList(args));
        try{
            //placeTicketService.asyncSendSms(reqPlaceMessageVo.getMobile(), SmsApi.MESSAGE_TEMPLATE_PLACE_PROMOTION_MESSAGE,args,true);
            placeSmsService.sendSms(mobileList,SmsApi.MESSAGE_TEMPLATE_PLACE_PROMOTION_MESSAGE, PlaceConstants.PLACE_SMS_TYPE_MESSAGE,paramList);
        }catch(Exception e){
            logger.info("短信发送失败-------->"+e.getMessage());
            result= APIResponse.returnFail("短信发送失败！");
        }
        result=APIResponse.returnSuccess();
        return result;
    }

    /*
     * 推广下发短信订单
     * @param reqPlaceOrderInfo
     * @return
     */
    @Async
    public APIResponse<?> promotionSave(ReqPlaceOrderInfo reqPlaceOrderInfo){
        String token=reqPlaceOrderInfo.getTokenFlag();
        String mobile=reqPlaceOrderInfo.getUserInfo().getMobile();
        List<TbBizPlacePromotionTimes> timesList=placeMessageService.getPromotionTimesByMobile(mobile);
        ReqPlaceOrderSearchVo  reqVo=new ReqPlaceOrderSearchVo();
        reqVo.setMobile(reqPlaceOrderInfo.getUserInfo().getMobile());
        reqVo.setOrder_status(PlaceConstants.ORDER_COMPLETE_PAY_STATUS);
        reqVo.setUseType(PlaceConstants.ORDER_USE_APP_BILLING);
        //查找该手机号有没在APP上订过场
        List<TbBizPlaceOrder> orderList=placeOrderService.getPlaceOrderList(reqVo);
        //保存初始APP订场次数
        if (timesList==null||timesList.size()<=0){
            TbBizPlacePromotionTimes vo=new TbBizPlacePromotionTimes();
            vo.setMobile(mobile);
            vo.setTimes(orderList.size());
            vo.setUserId(reqPlaceOrderInfo.getUid());//消费者uid
            placeMessageService.savePromotionTimes(vo);
        }
        //保存推广订单
        TbBizPlacePromotionRecord voVal= placeMessageService.getPromotionRecordByToken(token);
        TbBizPlacePromotionOrder vo=new TbBizPlacePromotionOrder();
        if (voVal!=null){
            //vo.setPlaceOrderId(respOrder.getData().getOrderNo());
            vo.setPlaceOrderId(reqPlaceOrderInfo.getPlaceOrderId());
            vo.setMobile(voVal.getMobile());
            vo.setPlaceId(voVal.getPlaceId());
            vo.setPromotionDate(voVal.getPromotionDate());
            vo.setAccountNumber(voVal.getAccountNumber());
            vo.setToken(voVal.getToken());
            vo.setPromotionRecordId(voVal.getId());
            vo.setCategoryId(reqPlaceOrderInfo.getCategoryId());
            List<TbBizPlaceOrderItem> itemList=placeOrderService.getTbBizPlaceOrderItem(vo.getPlaceOrderId());
            List<String> saleIdList=new ArrayList<>();
            for (TbBizPlaceOrderItem item:itemList){
                saleIdList.add(item.getSaleId());
            }
            List<TbBizPlaceUnitSalePlan> saleList=new ArrayList<>();
            if (saleIdList!=null&&saleIdList.size()>0){
                saleList=placeInnerService.getPlaceUnitSalePlanBySaleId(saleIdList);
            }
            List<Date> salePlanDateList=new ArrayList<>();
            //取出一个订单的场地消费开始时间
            for (TbBizPlaceUnitSalePlan plan:saleList){
                String date=DateUtils.transferDateToString(plan.getDate());
                String hour=DateUtils.transferHourDateToString(plan.getStartTime());
                String time=date+" "+hour;
                salePlanDateList.add(DateUtils.tranferStringToDate(time));
            }
            //冒泡排序，取出最小的订单开始时间
            if (salePlanDateList.size()>1){
                for (int i=0;i<salePlanDateList.size();i++){
                    for (int j=i+1;j<salePlanDateList.size();j++){
                        if (DateUtils.dateCompare(salePlanDateList.get(i), salePlanDateList.get(j),false)){
                            Date date=salePlanDateList.get(i);
                            salePlanDateList.set(i,salePlanDateList.get(j));
                            salePlanDateList.set(j,date);
                        }
                    }
                }
            }
            if (salePlanDateList!=null&&salePlanDateList.size()>0){
                vo.setConsumeDate(salePlanDateList.get(0));
            }
            vo.setOrderStatus((int)PlaceConstants.ORDER_PREPAY_STATUS);
            vo.setPromotionCount(0);
            vo.setSettleStatus((byte)0);
            vo.setRewardAmount(new BigDecimal(0));
            placeMessageService.savePromotionOrder(vo);
        }
        return APIResponse.returnSuccess();
    }

    /**
     * 推广下发短信二次订单
     * @param reqOrderPay
     * @return
     */
/*    public APIResponse<?> secondPromotionSave(ReqOrderPay reqOrderPay){
        String token=reqOrderPay.getTokenFlag();
        //通过订单号获取订单
        TbBizPlaceOrder order= placeOrderService.getOrderListByPlaceOrderId(reqOrderPay.getOrderNo());
        String mobile=order.getMobile();

        List<TbBizPlacePromotionTimes> timesList=placeMessageService.getPromotionTimesByMobile(mobile);
        ReqPlaceOrderSearchVo  reqVo=new ReqPlaceOrderSearchVo();
        reqVo.setMobile(mobile);
        reqVo.setPay_status(PlaceConstants.PAY_STATUS);
        reqVo.setOrder_status(PlaceConstants.ORDER_COMPLETE_PAY_STATUS);
        reqVo.setUseType(PlaceConstants.ORDER_USE_APP_BILLING);
        //查找该手机号有没在APP上订过场
        List<TbBizPlaceOrder> orderList=placeOrderService.getPlaceOrderList(reqVo);
        //保存初始APP订场次数
        if (timesList==null){
            TbBizPlacePromotionTimes vo=new TbBizPlacePromotionTimes();
            vo.setMobile(mobile);
            vo.setTimes(orderList.size());
            vo.setUserId(reqOrderPay.getUid());//消费者uid
            placeMessageService.savePromotionTimes(vo);
        }
        //保存推广订单
        TbBizPlacePromotionRecord voVal= placeMessageService.getPromotionRecordByToken(token);
        TbBizPlacePromotionOrder vo=new TbBizPlacePromotionOrder();
        if (voVal!=null){
            //vo.setPlaceOrderId(respOrder.getData().getOrderNo());
            logger.warn("reqPlaceOrderInfo.getOrderNo()订单号为空吗？？？？------->"+reqOrderPay.getOrderNo());
            logger.info("reqPlaceOrderInfo.getOrderNo()订单号为空吗？？？？------->"+reqOrderPay.getOrderNo());
            logger.info("reqPlaceOrderInfo.getPlaceId场馆ID为空吗？？？？------->"+order.getPlaceId());
            vo.setPlaceOrderId(reqOrderPay.getOrderNo());
            vo.setMobile(voVal.getMobile());
            vo.setPlaceId(voVal.getPlaceId());
            vo.setPromotionDate(voVal.getPromotionDate());
            vo.setAccountNumber(voVal.getAccountNumber());
            vo.setToken(voVal.getToken());
            vo.setPromotionRecordId(voVal.getId());
            vo.setCategoryId(order.getCategoryId());
            List<TbBizPlaceOrderItem> itemList=placeOrderService.getTbBizPlaceOrderItem(vo.getPlaceOrderId());
            List<String> saleIdList=new ArrayList<>();
            for (TbBizPlaceOrderItem item:itemList){
                saleIdList.add(item.getSaleId());
            }
            List<TbBizPlaceUnitSalePlan> saleList=new ArrayList<>();
            if (saleIdList!=null&&saleIdList.size()>0){
                saleList=placeInnerService.getPlaceUnitSalePlanBySaleId(saleIdList);
            }
            List<Date> salePlanDateList=new ArrayList<>();
            //取出一个订单的场地消费开始时间
            for (TbBizPlaceUnitSalePlan plan:saleList){
                String date=DateUtils.transferDateToString(plan.getDate());
                String hour=DateUtils.transferHourDateToString(plan.getStartTime());
                String time=date+" "+hour;
                salePlanDateList.add(DateUtils.tranferStringToDate(time));
            }
            //冒泡排序，取出最小的订单开始时间
            if (salePlanDateList.size()>1){
                for (int i=0;i<salePlanDateList.size();i++){
                    for (int j=i+1;j<salePlanDateList.size();j++){
                        if (DateUtils.dateCompare(salePlanDateList.get(i), salePlanDateList.get(j),false)){
                            Date date=salePlanDateList.get(i);
                            salePlanDateList.set(i,salePlanDateList.get(j));
                            salePlanDateList.set(j,date);
                        }
                    }
                }
            }
            if (salePlanDateList!=null&&salePlanDateList.size()>0){
                vo.setConsumeDate(salePlanDateList.get(0));
            }
            vo.setOrderStatus((int)PlaceConstants.ORDER_PREPAY_STATUS);
            vo.setPromotionCount(0);
            vo.setSettleStatus((byte)0);
            vo.setRewardAmount(new BigDecimal(0));
            placeMessageService.savePromotionOrder(vo);
        }
        return APIResponse.returnSuccess();
    }*/
}
